/*
 * UserNet  --  TCP/IP implementation in userspace
 * Copyright (C) 2010  Robert Millan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef UNET_MISC_H
#define UNET_MISC_H

#include <stdio.h>		/* vprintf */
#include <stdlib.h>		/* getenv */
#include <stdarg.h>		/* va_start, va_end */
#include <string.h>		/* strcmp */

#define COMPILE_TIME_ASSERT(cond)	extern int __compile_time_assert[(cond) ? 0 : -1] __attribute__ ((__unused__))

#define ARRAY_SIZE(array) (sizeof (array) / sizeof ((array)[0]))

#define HASH_HEAD(table,index)		((table)[(index) % ARRAY_SIZE(table)])

static inline void
debug_printf (const char *module, const char *format, ...)
{
  va_list args;
  char *debug = getenv ("UNET_DEBUG");

  if (debug && (!strcmp (debug, module) || !strcmp (debug, "all")))
    {
      va_start (args, format);
      vprintf (format, args);
      va_end (args);
    }
}

static inline void *
unet_zalloc (size_t size)
{
  void *ptr = malloc (size);
  if (ptr)
    memset (ptr, 0, size);
  return ptr;
}

/* Non-crappy version of inet_ntoa() */
#include <alloca.h>
#include <arpa/inet.h>
#define inet_ntoa(addr) inet_ntop (AF_INET, &(addr), alloca (INET_ADDRSTRLEN), INET_ADDRSTRLEN)

#endif
